package cosplay.DAO;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import cosplay.Beans.Votes;

@Repository (value="votedao")
public class VoteDAOImpl implements VoteDAO{
	@Autowired
	private JdbcTemplate jt;

	@Override
	public int add(final Votes vote) {
		// TODO Auto-generated method stub
		int id=0;
		if(vote!=null)
		{
			Object[] obj=(Object[]) jt.execute(
					new CallableStatementCreator(){

						@Override
						public CallableStatement createCallableStatement(
								Connection conn) throws SQLException {
							// TODO Auto-generated method stub
							String sql="CALL VOTE_ADD(?,?,?,?,?);";
							CallableStatement stm=conn.prepareCall(sql);
							stm.setInt(1, vote.getUserID());
							stm.setInt(2, vote.getResultID());
							stm.setInt(3, 1);
							stm.setString(4, vote.getVoteIP());
							stm.registerOutParameter(5, java.sql.Types.INTEGER);
							return stm;
						}}, new CallableStatementCallback(){

							@Override
							public Object doInCallableStatement(
									CallableStatement stm) throws SQLException,
									DataAccessException {
								// TODO Auto-generated method stub
								ResultSet rs=stm.executeQuery();
								Object[] obj=new Object[2];
								obj[0]=stm.getInt(5);
								obj[1]=rs;
								return obj;
							}});
			id=((Integer) obj[0]).intValue();
		}
		return id;
	}

	@Override
	public boolean delete(final int uid, final int rid) {
		// TODO Auto-generated method stub
		boolean sucess=false;
		if(uid*rid>0)
		{
			jt.execute(
					new CallableStatementCreator(){

						@Override
						public CallableStatement createCallableStatement(
								Connection conn) throws SQLException {
							// TODO Auto-generated method stub
							String sql="CALL VOTE_DELETE(?,?);";
							CallableStatement stm=conn.prepareCall(sql);
							stm.setInt(1, uid);
							stm.setInt(2, rid);
							return stm;
						}}, new CallableStatementCallback(){

							@Override
							public Object doInCallableStatement(
									CallableStatement stm) throws SQLException,
									DataAccessException {
								// TODO Auto-generated method stub
								ResultSet rs=stm.executeQuery();
								Object[] obj=new Object[2];
								obj[0]=null;
								obj[1]=rs;
								return obj;
							}});
			sucess=true;
		}
		return sucess;
	}
}
